package com.lomoye.netty.secondexample;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 2020/2/8 22:20
 * yechangjun
 */
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        DefaultEventExecutorGroup defaultEventExecutorGroup = new DefaultEventExecutorGroup(
                8,
                new ThreadFactory() {

                    private AtomicInteger threadIndex = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet());
                    }
                });

        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(defaultEventExecutorGroup, new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast(defaultEventExecutorGroup, new LengthFieldPrepender(4));
        pipeline.addLast(defaultEventExecutorGroup, new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(defaultEventExecutorGroup, new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(defaultEventExecutorGroup, new MyServerHandler());
    }
}
